package com.sjt.SDSLearn;

import java.util.Arrays;

/**
 * 简单动态字符串SDS
 */
public class SDS {
    //记录buf数组中已经使用的字节数量
    int len;
    //记录buf数组中剩余的空间
    int free;
    //保存实际字符串
    char[] buf;

    //初始化
    public SDS(String text) {
         this.len=text.length();
         buf=text.toCharArray();
         free=0;
    }

    //打印详细信息
    public void toPrint(){
        System.out.println("len:"+this.len);
        System.out.println("free:"+this.free);
        System.out.println("buf:"+ Arrays.toString(buf));
    }

    //拼接字符串
    public void append(String text)
    {   //如果当前剩余空间大于要拼接字符串的长度，就直接加到末尾
        if(this.free>=text.length())
        {
            System.arraycopy(text.toCharArray(),0,this.buf,len,text.length());
            this.len+=text.length();
            this.free=this.buf.length-this.len;
        }else{
             int newLen=this.len+text.length();
             if(newLen>=1024*1024)
             {
                 char[] newBuf=new char[1024*1024+newLen+1];
                 System.arraycopy(this.buf,0,newBuf,0,this.len);
                 System.arraycopy(text.toCharArray(),0,newBuf,this.len,text.length());
                 this.len=newLen;
                 this.free=1024*1024+newLen+1-this.len;
                 newBuf[1024*1024+newLen]='0';
                 this.buf=newBuf;
             }else{
                 char[] newBuf=new char[2*newLen+1];
                 System.arraycopy(this.buf,0,newBuf,0,this.len);
                 System.arraycopy(text.toCharArray(),0,newBuf,this.len,text.length());
                 this.len=newLen;
                 this.free=2*newLen+1-this.len;
                 newBuf[2*newLen]='0';
                 this.buf=newBuf;
             }
        }
    }
}

